import network
import urequests
import uos
import machine
import lib.sdcard as sdcard
from time import sleep

# Wi-Fi配置
WIFI_SSID = "Lanmei"
WIFI_PASSWORD = "Lanmei666"

# 图片URL
IMAGE_URL = "https://gaoimg.com/wp-content/uploads/2023/03/e847ba5d895a3222-1.jpg"  # 替换为实际图片URL

# SD卡配置 (根据你的硬件调整引脚)
SD_CS_PIN = 22  # CS引脚连接到GPIO5

def connect_wifi():
    """连接Wi-Fi"""
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    
    if not wlan.isconnected():
        print("正在连接Wi-Fi...")
        wlan.connect(WIFI_SSID, WIFI_PASSWORD)
        
        # 等待连接
        for _ in range(20):
            if wlan.isconnected():
                break
            sleep(1)
    
    if wlan.isconnected():
        print("Wi-Fi连接成功!")
        print("网络配置:", wlan.ifconfig())
        return True
    else:
        print("Wi-Fi连接失败!")
        return False

def init_sd_card():
    """初始化SD卡"""
    try:
        # 初始化SPI和SD卡
        spi = machine.SPI(1, baudrate=1000000, polarity=0, phase=0, bits=8, firstbit=machine.SPI.MSB,
                         sck=machine.Pin(18), mosi=machine.Pin(23), miso=machine.Pin(19))
        sd = sdcard.SDCard(spi, machine.Pin(SD_CS_PIN))
        
        # 挂载文件系统
        vfs = uos.VfsFat(sd)
        uos.mount(vfs, "/sd")
        
        print("SD卡初始化成功!")
        return True
    except Exception as e:
        print("SD卡初始化失败:", e)
        return False

def download_image(url, filename):
    """下载图片并保存到SD卡"""
    try:
        print("开始下载图片...")
        
        # 发送HTTP请求
        response = urequests.get(url)
        
        # 检查响应状态
        if response.status_code == 200:
            print("图片下载成功，正在保存...")
            
            # 保存到SD卡
            with open("/sd/" + filename, "wb") as f:
                f.write(response.content)
            
            print("图片已保存到SD卡:", filename)
            
            # 检查文件大小
            file_info = uos.stat("/sd/" + filename)
            print("文件大小:", file_info[6], "字节")
            
            return True
        else:
            print("下载失败，HTTP状态码:", response.status_code)
            return False
            
    except Exception as e:
        print("下载过程中出错:", e)
        return False
    finally:
        # 确保响应关闭
        if 'response' in locals():
            response.close()

def main():
    """主函数"""
    # 连接Wi-Fi
    if not connect_wifi():
        return
    
    # 初始化SD卡
    if not init_sd_card():
        return
    
    # 下载图片 (使用时间戳作为文件名避免重复)
    import utime
    filename = "image_{}.jpg".format(utime.time())
    
    if download_image(IMAGE_URL, filename):
        print("操作成功完成!")
    else:
        print("操作失败!")

# 运行主程序
if __name__ == "__main__":
    main()